<script setup>
import { ref, onMounted } from 'vue';

// 状态管理
const foodToReplenish = ref([]);
const familyMembersStatus = ref([]);
const tomorrowWeather = ref({});
const airConditionerStatus = ref('');
const bowlsToWash = ref(0);
const connectionStatus = ref('Disconnected');

// WebSocket连接
let ws;

// 连接WebSocket
function connectWebSocket() {
  // 关闭已有连接
  if (ws) {
    ws.close();
  }

  // 创建新连接
  ws = new WebSocket('ws://localhost:3000');

  // 连接打开
  ws.onopen = () => {
    console.log('WebSocket connected');
    connectionStatus.value = 'Connected';
  };

  // 接收消息
  ws.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);
      console.log('Received message:', data);

      // 处理不同类型的消息
      switch (data.type) {
        case 'connection':
          // 连接成功消息
          break;
        case 'foodToReplenish':
          foodToReplenish.value = data.data;
          break;
        case 'familyMembersStatus':
          familyMembersStatus.value = data.data;
          break;
        case 'tomorrowWeather':
          tomorrowWeather.value = data.data;
          break;
        case 'airConditionerStatus':
          airConditionerStatus.value = data.data.message;
          break;
        case 'bowlsToWash':
          bowlsToWash.value = data.data.count;
          break;
        case 'error':
          console.error('Error:', data.message);
          break;
      }
    } catch (error) {
      console.error('Error parsing message:', error);
    }
  };

  // 连接关闭
  ws.onclose = () => {
    console.log('WebSocket disconnected');
    connectionStatus.value = 'Disconnected';
    // 尝试重连
    setTimeout(connectWebSocket, 3000);
  };

  // 连接错误
  ws.onerror = (error) => {
    console.error('WebSocket error:', error);
    connectionStatus.value = 'Error';
  };
}

// 发送消息到后端
function sendMessage(type, data = {}) {
  if (ws && ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({
      type,
      ...data
    }));
  } else {
    console.error('WebSocket not connected');
  }
}

// 生命周期钩子 - 组件挂载时
onMounted(() => {
  connectWebSocket();
});
</script>

<template>
  <div class="app-container">
    <header>
      <h1>智能控制面板</h1>
      <div class="connection-status">{{ connectionStatus }}</div>
    </header>

    <main>
      <section class="panel-section">
        <h2>需要补充的食物</h2>
        <button @click="sendMessage('getFoodToReplenish')">获取食物清单</button>
        <div class="panel-content">
          <ul v-if="foodToReplenish.length > 0">
            <li v-for="food in foodToReplenish" :key="food.id">
              {{ food.name }} - 当前数量: {{ food.currentQuantity }}, 警戒线: {{ food.alertQuantity }}
            </li>
          </ul>
          <p v-else>暂无需要补充的食物</p>
        </div>
      </section>

      <section class="panel-section">
        <h2>家庭成员状态</h2>
        <button @click="sendMessage('getFamilyMembersStatus')">获取状态</button>
        <div class="panel-content">
          <ul v-if="familyMembersStatus.length > 0">
            <li v-for="member in familyMembersStatus" :key="member.id">
              {{ member.name }}: {{ member.status }}
            </li>
          </ul>
          <p v-else>暂无家庭成员状态信息</p>
        </div>
      </section>

      <section class="panel-section">
        <h2>明天天气</h2>
        <button @click="sendMessage('getTomorrowWeather')">获取天气</button>
        <div class="panel-content">
          <div v-if="Object.keys(tomorrowWeather).length > 0">
            <p>温度: {{ tomorrowWeather.temperature }}</p>
            <p>状况: {{ tomorrowWeather.condition }}</p>
            <p>风力: {{ tomorrowWeather.wind }}</p>
          </div>
          <p v-else>暂无天气信息</p>
        </div>
      </section>

      <section class="panel-section">
        <h2>空调控制</h2>
        <div class="control-group">
          <button @click="sendMessage('turnOnAirConditioner', { deviceCount: 1 })" class="ac-button">
            开启单个空调
          </button>
          <button @click="sendMessage('turnOnAirConditioner', { deviceCount: 3 })" class="ac-button">
            开启多个空调
          </button>
        </div>
        <div class="panel-content">
          <p>{{ airConditionerStatus }}</p>
        </div>
      </section>

      <section class="panel-section">
        <h2>厨房碗碟</h2>
        <button @click="sendMessage('getBowlsToWash')">获取碗碟数量</button>
        <div class="panel-content">
          <p>需要清洗的碗碟数量: {{ bowlsToWash }}</p>
        </div>
      </section>
    </main>
  </div>
</template>

<style scoped>
.app-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ccc;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

.connection-status {
  padding: 5px 10px;
  border-radius: 15px;
  font-size: 0.8em;
  font-weight: bold;
}

.connection-status.Connected {
  background-color: #4CAF50;
  color: white;
}

.connection-status.Disconnected {
  background-color: #f44336;
  color: white;
}

main {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.panel-section {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.panel-section h2 {
  margin-top: 0;
  font-size: 1.2em;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
  margin-bottom: 15px;
}

button {
  background-color: #2196F3;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 15px;
}

button:hover {
  background-color: #0b7dda;
}

.control-group {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.ac-button {
  flex: 1;
}

.panel-content {
  min-height: 100px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  padding: 5px 0;
  border-bottom: 1px solid #eee;
}
</style>
